//
//  RecommendPicsDetail.m
//  AutoHome
//
//  Created by wqh on 15-5-16.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "RecommendPicsDetail.h"

#import "PicCell.h"
#import "PicModel.h"

#define kPicCellId @"PicCellId"
@interface RecommendPicsDetail ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic) NSMutableArray *dataArr;
@property (nonatomic) NSDictionary *categorys;
@property (nonatomic) NSString *totalCount;

@property (nonatomic,assign) NSInteger pageIndex1;
@property (nonatomic,assign) NSInteger pageIndex2;
@property (nonatomic,assign) NSInteger pageIndex3;
@property (nonatomic,assign) NSInteger pageIndex4;
@property (nonatomic,assign) NSInteger pageIndex5;

@property (nonatomic) NSMutableArray *categorysArr;

@end

@implementation RecommendPicsDetail

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.categorysArr = [NSMutableArray array];
    self.view .backgroundColor = [UIColor whiteColor];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    [self showUI];
    [self initData];
}
#pragma mark - private method
//返回按钮触发 返回
- (IBAction)backButtonClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//下载按钮触发下载
- (IBAction)downloadPic:(UIButton *)sender {
    
   
    dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSInteger currentIndex =  self.collectionView.contentOffset.x/kScreenWidth;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.dataArr[currentIndex] imgurl]]];
        UIImage *image = [UIImage imageWithData:data];
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
    
    
    
    
//    UIImage *image = [UIImage imageNamed:@"about_icon_logo"];
//    
    
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    NSString *msg = nil;
    if (error != NULL) {
        msg = @"图片保存失败";
    }else {
        msg = @"图片保存成功";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show  ];
}

- (void)initData {
    self.dataArr = [NSMutableArray array];
    /*
     "3545㊣19469㊣http://car0.autoimg.cn/car/upload/2015/4/20/t_20150420223220156-1112.jpg,http://car0.autoimg.cn/car/upload/2015/4/20/t_20150420223210640-1110.jpg,http://car0.autoimg.cn/car/upload/2015/4/20/t_20150420223208250-1112.jpg"
     */
    
    NSString *str = self.model.indexdetail;
    NSRange range = [str rangeOfString:@"http://"];
    
    NSString *idStr = [str substringToIndex:range.location];
    
    NSArray *idArr = [idStr componentsSeparatedByString:@"㊣"];
    
    
    [[DataEngine sharedInstance] requestPicsDataWithId:idArr[0] :idArr[1] success:^(id respondsData) {
        [self downloadDataSuccess:respondsData];
    } failed:^(NSError *error) {
        
    }];
}

- (void)downloadDataSuccess:(id)respondsData {
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:respondsData options:NSJSONReadingMutableContainers error:nil];
    self.totalCount = dict[@"result"][@"rowcount"];
    self.categorys = dict[@"result"][@"categorys"];
    
    NSArray *array = dict[@"result"][@"categorys"];
    for (NSDictionary *dic in array) {
        [self.categorysArr addObject:dic[@"piccount"]];
    }
    
    self.titleLabel.text = [NSString stringWithFormat:@"1/%@",self.totalCount];
    
    for (NSDictionary *picDict in dict[@"result"][@"list"]) {
        PicModel *model = [PicModel new];
        [model setValuesForKeysWithDictionary:picDict];
        [self.dataArr addObject:model];
    }
   
    [self.collectionView reloadData];
}

- (void)showUI {
    
    self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
   
    self.seg.frame = CGRectMake(0, kScreenHeight-49, kScreenWidth, 49);
    self.seg.backgroundColor = [UIColor grayColor];
    self.seg.tintColor = [UIColor blackColor];
    self.topView.frame = CGRectMake(0, 20, kScreenWidth, 44);
    self.topView.backgroundColor = [UIColor blackColor];
    [self createCollectionView];
}
- (void)createCollectionView {
    self.collectionView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight);
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.pagingEnabled = YES;
    [self.collectionView registerNib:[UINib nibWithNibName:@"PicCell" bundle:nil] forCellWithReuseIdentifier: kPicCellId];
    self.collectionView.delegate =self;
    self.collectionView.dataSource =self;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PicCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kPicCellId forIndexPath:indexPath];
    PicModel *model = self.dataArr[indexPath.row];
    [cell.photoView.img sd_setImageWithURL:[NSURL URLWithString:model.imgurl] placeholderImage:[UIImage imageNamed:@"black_default_640_320"]];
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //减速停止
    NSInteger pageIndex = (NSInteger)(scrollView.contentOffset.x/kScreenWidth+1);
    self.titleLabel.text = [NSString stringWithFormat:@"%d/%@",pageIndex,self.totalCount];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger pageIndex = (NSInteger)(scrollView.contentOffset.x/kScreenWidth+1);
    if (0<=pageIndex <([self.categorysArr[0] integerValue])) {
        self.seg.selectedSegmentIndex = 0;
    }
    if ([self.categorysArr[0] integerValue] < pageIndex) {
        self.seg.selectedSegmentIndex = 1;
    }
    if ([self.categorysArr[1] integerValue] + [self.categorysArr[0] integerValue] < pageIndex) {
        self.seg.selectedSegmentIndex = 2;
    }
    if ([self.categorysArr[1] integerValue] + [self.categorysArr[0] integerValue] + [self.categorysArr[2] integerValue] < pageIndex) {
        self.seg.selectedSegmentIndex = 3;
    }
    
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)segClick:(UISegmentedControl *)sender {
    
    switch (sender.selectedSegmentIndex) {
        case 0:
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            self.titleLabel.text = [NSString stringWithFormat:@"1/%@",self.totalCount];
        }
            break;
        case 1:
        {
            NSInteger index = [self.categorysArr[0] integerValue] ;
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            
            self.titleLabel.text = [NSString stringWithFormat:@"%d/%@",index+1,self.totalCount];
            
        }
            break;
        case 2:
        {
            
            NSInteger index = [self.categorysArr[0] integerValue] +[self.categorysArr[1] integerValue];
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            
            self.titleLabel.text = [NSString stringWithFormat:@"%d/%@",index+1,self.totalCount];
        }
            break;
        case 3:
        {
            NSInteger index = [self.categorysArr[0] integerValue] +[self.categorysArr[1] integerValue] + [self.categorysArr[2] integerValue];
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            
            self.titleLabel.text = [NSString stringWithFormat:@"%d/%@",index+1,self.totalCount];
        }
            break;
        case 4:
        {
            if (![[self.categorysArr[4] stringValue] isEqualToString:@"0"]) {
                NSInteger index = [self.categorysArr[0] integerValue] +[self.categorysArr[1] integerValue] + [self.categorysArr[2] integerValue]+[self.categorysArr[3] integerValue];
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
                
                [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                
                self.titleLabel.text = [NSString stringWithFormat:@"%d/%@",index+1,self.totalCount];
            }
        }
            break;
        
            
        default:
            break;
    }
    
}
@end
